<template>
  <div style="display: flex; flex-direction: column; row-gap: 5px; margin-top: 5px">
    <div
      style="
        height: 60px;
        background: lightgray;
        border-radius: 4px;
        align-items: center;
        display: flex;
      "
    >
      <a-upload :before-upload="beforeUpload" @change="handleChange">
        <a-button style="margin-left: 10px">
          <upload-outlined></upload-outlined>
          upload
        </a-button>
      </a-upload>

      <a-button style="margin-left: 5px" @click="ontestDistanceMark">
        <aim-outlined></aim-outlined>
        Distance
      </a-button>

      <a-button style="margin-left: 5px" @click="onTestTextMarker">
        <aim-outlined></aim-outlined>
        ImageTextMarker
      </a-button>
      <a-button ref="testHeatmapRef" style="margin-left: 5px" @click="testFullHeatmap">
        <aim-outlined></aim-outlined>
        testFullHeatmap
      </a-button>
      <a-button ref="testHeatmapRef" style="margin-left: 5px" @click="testHeatmap">
        <aim-outlined></aim-outlined>
        testHeatmap
      </a-button>
      <a-button style="margin-left: 5px" @click="testSSE"> testSSE </a-button>
    </div>
    <div style="flex: 1; margin-bottom: 15px">
      <FhcLeaflet
        :map-id="'homeMapId'"
        :full-screen="true"
        :heatmap-data="heatmapData"
        :image-obj="imageObj"
        :is-full-heatmap="isFullheatmap"
        @on-map-created="onMapDivCreatedImpl"
      >
      </FhcLeaflet>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, onActivated, onDeactivated, getCurrentInstance } from 'vue'
import { render, h, ref } from 'vue'
import TestDistanceView from './TestDistanceView.vue'
import { UploadOutlined, AimOutlined } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { L, FhcLeaflet } from '../components/FhcLeaflet/index'
import {
  testDistanceMarkDiv,
  testDistanceVNode,
  getImageTextMarker,
  xy
} from '../components/FhcLeaflet/src/FhcLeaflet'
import { testFloorImg } from './testFloorImage'
import type { StoreData } from '@/components/Heatmap'
const testHeatmapRef = ref(null)
const isFullheatmap = ref<boolean | undefined>(undefined)
const instance = getCurrentInstance()

onMounted(() => {
  imageObj.value = testFloorImg
  console.log('testHeatmapRef', testHeatmapRef.value)
  console.log('testHeatmapRef', instance?.refs)
})

onUnmounted(() => {})

onActivated(() => {
  console.log('onActivated')
})

onDeactivated(() => {
  console.log('onDeactivated')
  if (mapTimer) {
    clearTimeout(mapTimer)
  }
})

let mapTimer: number | undefined

const pixelsRef = ref(0)

async function ontestDistanceMark() {
  const testDistanceView = h(TestDistanceView, {
    pixelsRef: pixelsRef,
    onSaveDistance: (data: { pixels: number; distance: string }) => {
      console.log('ontestDistanceMark data  disMM', data)
    }
  })
  testDistanceVNode(
    map!,
    testDistanceView,
    function (pixels: number, _mark1: L.Marker, _mark2: L.Marker, _polylineDistance: L.Polyline) {
      pixelsRef.value = pixels
      console.log('ontestDistanceMark', pixels)
    }
  )

  // res = testDistanceMarkDiv(map!, undefined, undefined, undefined, function (divEle, disM, callback) {
  //   console.log('aaaa', disM)
  //   ttttt(divEle, disM)
  //     .then(function (data) {
  //       console.log('Promise then >>>:' + data)
  //       callback(data + '')
  //     })
  //     .catch(function (reason) {
  //       console.log('rejected')
  //       callback(reason)
  //     })
  // })
}

function ttttt(divEle: HTMLDivElement, disM: string) {
  return new Promise((resolve, reject) => {
    let aa = true
    if (aa) {
      setTimeout(() => {
        const a = h(TestDistanceView, {
          pixelsRef: pixelsRef,
          onSaveDistance: (data: { distance: string }) => {
            console.log('data  disMM', data)
          }
        })
        render(a, divEle)
        resolve('(Promise resolve 11111)')
      }, 2000)
    } else {
      reject('failure reason')
    }
  })
}

function onTestTextMarker() {
  getImageTextMarker(
    {
      key: 1,
      mkImage: '/resource/svg/map_pin_red.svg',
      mkImageWH: 20
    },
    xy(500, 500),
    map!
  )
  getImageTextMarker(
    {
      key: 2,
      mkImage: '/resource/svg/map_pin_blue.svg',
      mkImageWH: 40,
      mkText: 'blue',
      mkFontSize: 20
    },
    xy(1000, 1000),
    map!
  )
}
let map: L.Map | null
function onMapDivCreatedImpl(_map: L.Map) {
  console.log('onMapDivCreatedImpl', map)
  map = _map
  // MapObj.map = map
  // MapObj.map.imageMapWidth = 8192
  // MapObj.map.imageMapHeight = 4380
}

//----------------------------------------------------------------

const minW = 800
const minH = 600
const heatmapData = ref<StoreData>({
  max: 100,
  min: 0,
  data: []
})
const imageObj = ref<{ src: string; height: number; width: number } | null>(null)
const fileList = ref<any[]>([])
const handleChange = ({ file, fileList }: UploadChangeParam) => {
  if (file.status !== 'uploading') {
    console.log(file, fileList)
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  fileList.value = [...fileList.value, file]
  console.log('beforeUpload中：', file)
  const isJpgOrPng = file['type'] === 'image/jpeg' || file['type'] === 'image/png'
  if (!isJpgOrPng) {
    message.error(`${file.name} is not a png or jpeg file`)
    return false
  }
  const maxM = 5
  const isLess5M = file['size'] < 1024 * 1024 * maxM
  if (!isLess5M) {
    message.error(`Image size is more than ${maxM}M`)
    return false
  }

  let reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    var uploadListDiv = document.getElementsByClassName(
      'ant-upload-list ant-upload-list-text'
    )[0] as HTMLDivElement

    if (uploadListDiv && uploadListDiv.parentNode) {
      uploadListDiv.parentNode.removeChild(uploadListDiv) //不移除会显示红色error cannot post 404？？
      //移除就不用'inline-flex'设置了，'inline-flex'设置主要是把选择地图按钮和显示文件名称同一行
    }

    const image = new Image()
    image.src = reader.result as string
    image.onload = () => {
      if (map) {
        console.log('333333333333', image.width, image.height)
        if (image.width < minW || image.height < minH) {
          message.error(`Image width cannot less than ${minW} and height cannot less than ${minH}`)
          return false
        } else {
          imageObj.value = { src: image.src, width: image.width, height: image.height }
        }
      }
    }
  }
  return true
}

// function setMarker() {
//   let rect = document.getElementById(mapId)?.getBoundingClientRect()
//   let scale = 1
//   let mapDivW = minW
//   // let mapDivH = minH
//   if (rect && rect.width && rect.height) {
//     mapDivW = rect.width
//     // mapDivH = rect.height
//     scale = MapObj.mapImgW / mapDivW
//   }
//   let iconW = 20
//   let iconH = 30
//   let iconDiv = `<div style="background:red;width:${iconW}px;height:${iconH}px"></div>`

//   var icon = L.divIcon({
//     html: iconDiv,
//     iconSize: [iconW, iconH], // size of the icon
//     iconAnchor: [iconW / 2, iconH / 2], // 要考虑svg本身的padding
//     popupAnchor: [iconW, iconH] // point from which the popup should open relative to the iconAnchor
//   })
//   if (MapObj.map) {
//     for (let i = 0; i < 10; i++) {
//       let mk = L.marker(xy(i * 40 * scale, i * 30 * scale), {
//         icon: icon
//       }).addTo(MapObj.map)
//     }
//   }
// }
let eventSSE: EventSource | null = null
function testSSE() {
  // readyState: 0->Connecting, 1->Open，2->Closed
  if (eventSSE) {
    if (eventSSE.readyState == 0) {
      return
    } else if (eventSSE.readyState == 1) {
      eventSSE.close()
      eventSSE = null
      return
    }
  }

  const token = window.localStorage.getItem('token')
  const url = 'http://127.0.0.1:3000/sse/sseStart' + '?token=' + token
  console.log('EventSource:', url)
  eventSSE = new EventSource(url)
  eventSSE.addEventListener('open', (e) => {
    console.log('testSSE open:', e)
  })
  eventSSE.addEventListener('message', (e: MessageEvent<any>) => {
    const { code, data } = JSON.parse(e.data)
    // console.log('testSSE message:', code, data)

    if (isFullheatmap.value != undefined && heatmapData.value.data.length < 6000) {
      let pppX = map!.imageMapWidth + 1000
      let pppY = map!.imageMapHeight + 1000

      const point = {
        x: Math.floor(Math.random() * pppX) - 500,
        y: Math.floor(Math.random() * pppY) - 500,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
  })
  eventSSE.addEventListener('error', (e) => {
    console.log('testSSE error:', e)
  })
  eventSSE.addEventListener('close', (e) => {
    console.log('testSSE close:', e)
  })
}

//----------------------------------------------------------------
function testHeatmap() {
  if (isFullheatmap.value == undefined || isFullheatmap.value == true) {
    heatmapData.value.data = []
    isFullheatmap.value = false
  }

  if (heatmapData.value.data.length < 5000) {
    for (let i = 0; i < 1000; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1,
        y: Math.floor(Math.random() * pppY) + 1,
        value: Math.floor(Math.random() * 100) + 1
      }
      heatmapData.value.data.push(point)
    }
  } else {
    heatmapData.value.data = []
  }
}
function testFullHeatmap() {
  if (isFullheatmap.value == undefined || isFullheatmap.value == false) {
    isFullheatmap.value = true
    heatmapData.value.data = []
  }

  if (heatmapData.value.data.length < 5000) {
    for (let i = 0; i < 500; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1,
        y: Math.floor(Math.random() * pppY) + 1,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
    for (let i = 0; i < 100; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1 - i * 10 - 200,
        y: Math.floor(Math.random() * pppY) + 1 - i * 10 - 200,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
    for (let i = 0; i < 200; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1 + i * 10 + 200,
        y: Math.floor(Math.random() * pppY) + 1 + i * 10 + 200,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
    for (let i = 0; i < 100; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1 + i * 10 + 500,
        y: Math.floor(Math.random() * pppY) + 1 - i * 10 - 400,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
    for (let i = 0; i < 100; i++) {
      let pppX = map!.imageMapWidth
      let pppY = map!.imageMapHeight

      const point = {
        x: Math.floor(Math.random() * pppX) + 1 - 500,
        y: Math.floor(Math.random() * pppY) + 1 + 400,
        value: Math.floor(Math.random() * 100) + 1
      }

      heatmapData.value.data.push(point)
    }
  } else {
    heatmapData.value.data = []
  }
}
</script>
<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>
